﻿using PagedList;
using PagedList.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GiaoTrinhEPU.Repositories.Repositories;
using GiaoTrinhEPU.Repositories.DataModels;
using GiaoTrinhEPU.Repositories;
using GiaoTrinhEPU.Repositories.Interfaces;
using GiaoTrinhEPU.Core.ActionResults;
using GiaoTrinhEPU.Core;

namespace GiaoTrinhEPU.Areas.Manager.Controllers
{
    public class DepartmentController : BaseController
    {
        /// <summary>
        /// Declare Department Repository
        /// </summary>
        private DepartmentRepository departmentRepository;

        /// <summary>
        ///  Declare Session
        /// </summary>
        public static string SessionDepartmentSort = "SessionDepartmentSort";
        public static string SessionDepartmentSearch = "SessionDepartmentSearch";
        public static string SessionDepartmentSortOpt = "SessionDepartmentSortOpt";



        // GET: /Department/
        /// <summary>
        /// Constructor that allow to create a Comment controller
        /// </summary>
        public DepartmentController()
            : base()
        {
            this.departmentRepository = new DepartmentRepository();
            ViewBag.SelectedMenuId = 25;
        }

        public ActionResult Index(int page = 1, int size = 25, String search = "", String opt = "", String sort = "")
        {
            ViewBag.Title = "Khoa";
            // Stored Session
     
            Session[SessionDepartmentSort] = sort.Trim().Length > 0 ? sort.ToLower() : Session[SessionDepartmentSort];
            Session[SessionDepartmentSortOpt] = opt.Trim().Length > 0 ? opt.ToLower() : Session[SessionDepartmentSortOpt];

            var department = this.departmentRepository.ListDepartments(false).ToList();

            // Search
            if (Session[SessionDepartmentSearch] != null)
            {
                ViewBag.Keyword = Session[SessionDepartmentSearch].ToString();

                department = department.Where(l => l.Name.ToUpper().Contains(ViewBag.Keyword.ToUpper())).ToList(); 

            }
            // Sort 
            ViewBag.SortNameOpt = "desc";
            if (Session[SessionDepartmentSort] != null)
            {
                switch (Session[SessionDepartmentSort].ToString())
                {
                    case "name":
                        department = Session[SessionDepartmentSortOpt].ToString().Equals("desc") ? department.OrderByDescending(s => s.Name).ToList() : department.OrderBy(s => s.Name).ToList();

                        Session[SessionDepartmentSort] = "name";
                        ViewBag.SortNameOpt = Sort.SetSortOrderOption(Session[SessionDepartmentSortOpt].ToString());
                        break;

                    default:
                        break;
                }
            }


            return View(department.ToPagedList(page, size));
        }
        /// <summary>
        /// Get
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Create()
        {
            return View();
        }
        /// <summary>
        /// create action with param
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(DepartmentModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Create");
            }
            else
            {
                if (this.departmentRepository.HasNameExisted(model.Name) == true)
                {
                    return View("Create").WithErrorMessage("Tên khoa đã được sử dụng");
                }


                var department = new Department();
                department.Id = (int)model.Id;
                department.Name = model.Name;
                department.Description = model.Description;

                this.departmentRepository.CreateDepartment(department);
                // Returns view with successful message
                return RedirectToAction("Index").WithSuccessMessage("Đã tạo thành công khoa mới"); ;
            }
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Edit(int id = 0)
        {
            ViewBag.EnabledMenu = false;

            var department = this.departmentRepository.GetDepartmentById(id);
            var departmentModel = new DepartmentModel(department);

            // population dropdow list


            return View(departmentModel);
        }
        /// <summary>
        ///  Edit action 
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(DepartmentModel model)
        {
            ViewBag.EnabledMenu = false;

            if (!ModelState.IsValid)
            {
                return View("Edit");
            }
            else
            {
                if (this.departmentRepository.HasNameDuplicated(model.Id, model.Name) == true)
                {
                    return View("Edit").WithErrorMessage("Tên khoa đã được sử dụng");
                }

                var department = new Department();

                department.Id = (int)model.Id;
                department.Name = model.Name;
                department.Description = model.Description;

                this.departmentRepository.UpdateDepartment(department);

                return RedirectToAction("Index").WithSuccessMessage("Đã sửa thành công khoa này");

            }
        }
        /// <summary>
        /// Delete action 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Delete(int id)
        {
            this.departmentRepository.DeleteDepartment(id);
            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công khoa này"); ;
        }

        /// <summary>
        ///  Delete Multi
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DeleteMulti(int[] ids = null)
        {
            if (ids == null || ids.Length == 0)
            {
                return RedirectToAction("Index");
            }

            for (int i = 0; i < ids.Length; i++)
            {
                int id = ids[i];

                this.departmentRepository.DeleteDepartment(id);
            }

            return RedirectToAction("Index").WithSuccessMessage("Đã xóa thành công những khoa này");
        }
        /// <summary>
        /// Clear
        /// </summary>
        /// <returns></returns>
        public ActionResult Clear()
        {
            // Clear sessions
            Session[SessionDepartmentSearch] = null;
            Session[SessionDepartmentSort] = null;
            Session[SessionDepartmentSortOpt] = null;

            return RedirectToAction("Index");
        }
        /// <summary>
        /// check name avaiable
        /// </summary>
        /// <param name="name"></param>
        /// <param name="Id"></param>
        /// <returns></returns>
        public JsonResult IsNameAvaiable(String name, int Id = 0)
        {
            if (Id == 0)
            {
                if (!this.departmentRepository.HasNameExisted(name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }
            }
            else
            {
                if (!this.departmentRepository.HasNameDuplicated(Id, name))
                {
                    return Json(true, JsonRequestBehavior.AllowGet);
                }


            }

            return Json("Tên khoa đã được sử dụng", JsonRequestBehavior.AllowGet);
        }
    }
}
